<template>
  <t-dialog
    :header="`${header}-${isEdit ? '修改设备' : '添加设备'}`"
    :visible.sync="visible"
    :onClose="closeDialog"
    :closeOnOverlayClick="false"
    confirmBtn="确定"
    :onConfirm="onSubmit"
    width="80%"
    top="5%"
  >
    <div id="main">
      <t-loading text="加载中..." :fullscreen="false" attach="#main" :loading="applyLoading" size="medium"> </t-loading>
      <div>
        <!-- 基本信息 -->
        <t-form ref="form" :data="formData" :rules="rules" labelWidth="180px">
          <t-row style="align-items: stretch; width: 99%" :gutter="14">
            <t-col :span="12">
              <t-card size="medium" title="基本信息">
                <t-row style="align-items: stretch" :gutter="14">
                  <t-col :span="6">
                    <t-form-item label="投入时间：" name="year">
                      <t-date-picker style="width: 390px" v-model="formData.year"></t-date-picker>
                    </t-form-item>
                    <t-form-item label="设备名称：" name="name">
                      <t-input
                        style="width: 390px"
                        placeholder="请输入型号"
                        clearable
                        v-model="formData.name"
                      ></t-input>
                    </t-form-item>
                    <t-form-item label="型号" name="model">
                      <t-input
                        style="width: 390px"
                        placeholder="请输入型号"
                        clearable
                        v-model="formData.model"
                      ></t-input>
                    </t-form-item>
                    <t-form-item label="数量：" name="count">
                      <t-input-number
                        style="width: 390px"
                        placeholder="请输入型号"
                        clearable
                        v-model="formData.count"
                        :min="0"
                      ></t-input-number>
                    </t-form-item>
                    <t-form-item label="主要用途：" name="mainUse">
                      <t-input
                        style="width: 390px"
                        placeholder="请输入主要用途"
                        clearable
                        v-model="formData.mainUse"
                      ></t-input>
                    </t-form-item>
                  </t-col>
                  <t-col :span="6">
                    <t-form-item label="添置方式：" name="addMethod">
                      <t-select
                        style="width: 390px"
                        v-model="formData.addMethod"
                        clearable
                        placeholder="请选择添置方式："
                        :options="dict.type.add_method"
                      >
                      </t-select>
                    </t-form-item>
                    <t-form-item label="单价(万元)：" name="price">
                      <t-input-number
                        style="width: 390px"
                        placeholder="请输入单价(万元)"
                        clearable
                        v-model="formData.price"
                        :min="0"
                      ></t-input-number>
                    </t-form-item>
                    <t-form-item label="研发场地面面积(m2)：" name="siteArea">
                      <t-input-number
                        style="width: 390px"
                        placeholder="请输入研发场地面面积(m2)"
                        clearable
                        v-model="formData.siteArea"
                        :min="0"
                      ></t-input-number>
                    </t-form-item>
                    <t-form-item label="备注：" name="note">
                      <t-input
                        style="width: 390px"
                        placeholder="请输入备注"
                        clearable
                        v-model="formData.note"
                      ></t-input>
                    </t-form-item>
                  </t-col>
                </t-row>
              </t-card>
            </t-col>
          </t-row>
        </t-form>
      </div>
    </div>
  </t-dialog>
</template>

<script>
import { getDictList } from "@/api/system/dict/data";
import {getFiles} from "@/api/common";

import { TODAY } from '@/utils/date';
import dayjs from "dayjs";
import {getIdCardBirthday} from "@/utils/common";


export default {
  name: "people-apply",
  components: {
  },
  dicts: ["formulate_type","standard_category","standard_property", "add_method"],
  props: {
    header: String,
    objId: [String, Number],
    row: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      profTitOptions:[],
      deptMenuOptions:[],
      dictTypes: {},
      nameOptions:[],
      leaderLoading:false,
      subBtnLoading:false,
      reviseNumDisable:true,
      active:1,
      subType:2,
      applyLoading: false,
      maxlength: 1000,
      lengthLimitObj: {
        description: 0
      },
      tinymceFlag: 1,
      dayjs,
      isEdit:false,
      formData: {
        id: Date.parse(new Date()),
        platformId:this.objId,
        year: null,
        name: null,
        model: null,
        count: null,
        mainUse: null,
        addMethod: null,
        price: null,
        siteArea: null,
        note: null,
      },
      visible: true,
      rules: {
        year: [
          {
            required: true,
            message: "投入时间不能为空",
          },
        ],
        name:[
          {
            required: true,
            message: "设备名称不能为空",
          },
        ],
        model:[
          {
            required: true,
            message: "型号不能为空",
          },
        ],
        count:[
          {
            required: true,
            message: "数量不能为空",
          },
        ],
        mainUse:[
          {
            required: true,
            message: "主要用途不能为空",
          },
        ],
        addMethod:[
          {
            required: true,
            message: "添置方式不能为空",
          },
        ],
        price:[
          {
            required: true,
            message: "单价(万元)不能为空",
          },
        ],
        siteArea:[
          {
            required: true,
            message: "研发场地面面积(m2)不能为空",
          },
        ],
      },
    }
  },
  async mounted() {
    await this.getDataTypes()
  },
  async created() {
    await this.getDeptTreeSelect(this.$store.state.user.deptId)
    this.isEdit = !!this.row.id
    Object.assign(this.formData, this.row)
    // 判断路由有没有id传过来
    // 有id则是修改需要回显数据，无id则是新增

  },
  methods: {
    onProfTitIdChange(val, content) {
      this.formData.profTit = content.node.data.level;
    },
    getDataTypes() {
      return getDictList(["project_type", "subject_classification", "sys_user_sex", "prof_tit", "degree", "education", "duty", "platform_type", "expect_result_type"]).then(response => {
        this.dictTypes = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    onIdCardChange(val) {
      const birthday = getIdCardBirthday(val);
      if (birthday !== "") {
        this.formData.birthDate = birthday.slice(0, 7);
      }
    },
    onLeaderNameChange(val,content) {
      const index = this.nameOptions.findIndex(val=>content?.option?.id === val.id)
      this.nameOptions[index].label= this.nameOptions[index].name;
      this.$set(this.nameOptions,index,this.nameOptions[index])
      // Object.assign(this.formData.projectLeader, content.option)
      const oldId = this.formData.id;
      let year = this.formData.year
      Object.assign(this.formData, content.option || this.nameOptions[index])
      this.formData.year = year
      this.formData.id = oldId;
    },
    createProjectLeaderOptions(value){
      this.nameOptions.push({
        label:`${value}`,
        value,
        name: value
      });
    },
    remoteProjectLeaderMethod(search){
      this.leaderLoading = true;
      this.$api.system.member.searchList({name:search}).then(response => {
        this.nameOptions = response.data.map(val=>  ({
          ...val,
          label:`${val.name}-${val.idCard}`,
          value: `${val.name}-${val.idCard}`,
        }));
        this.leaderLoading = false;
      }).catch((e) => {
        this.leaderLoading = false;
        this.$message.error(e.toString());
      });
    },
    getDeptTreeSelect() {
      return this.$api.system.dept.treeSelectAllIn().then(response => {
        this.deptMenuOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    filterByTree(val, tree, children = "children", id = "id", label = "label") {
      let text = '';
      const convert = (arr) => {
        arr.filter((item) => {
          if (item[id] === val) {
            text = item[label]
          } else if (item[children]) {
            return convert(item[children])
          }
          return false
        })
      }
      convert(tree)
      return text
    },
    onSubmit() {
      this.$refs.form.validate().then(async (validateResult) => {
        if (validateResult === true) {
          // 路由有id修改，没有新增
          if (this.isEdit) {
            const message = "修改成功"
            this.subBtnLoading = true
            this.$api.tjpt.equipment.edit(this.formData).then(response => {
              this.subBtnLoading =false
              this.$message.success(message)
              this.$emit("reload")
              this.closeDialog()
            }).catch(e => {
              this.subBtnLoading =false
              this.$message.error(e.toString())
            })
          } else {
            const message = "提交成功"
            this.subBtnLoading = true
            console.log(this.formData)
            this.$api.tjpt.equipment.add(this.formData).then(response => {
              this.subBtnLoading =false
              this.$message.success(message)
              this.$emit("reload")
              this.closeDialog()
            }).catch(e => {
              this.subBtnLoading =false
              this.$message.error(e.toString())
            })
          }
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      });
    },
    closeDialog() {
      this.$emit('update:visible', false);
    },
  }
}
</script>